package dailytest;

import org.bouncycastle.crypto.RuntimeCryptoException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.Security;

/**
 * @author yingxin
 * @description 描述: HmacSm3认证签名生成工具类
 * @date 2021/10/20 19:06
 */
public class Sm3Utils {


    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String encrytHmacSm3(String secret, String content) {
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSm3");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            long gmtDate = System.currentTimeMillis() / 1000;
            mac.update(("" + gmtDate + "\n").getBytes(StandardCharsets.UTF_8));
            mac.update(content.getBytes("UTF-8"));
            byte[] digest = mac.doFinal();
            return gmtDate + ":" + DatatypeConverter.printHexBinary(digest).toLowerCase();
        } catch (Exception e) {
            throw new RuntimeCryptoException("加密异常");
        }

    }




}

